﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DHLPricing.OrderServices;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Threading;

namespace DHLPricing.OrderInfo
{
    public partial class OrderImport : Form
    {
        static List<Orders> importOrdersList = new List<Orders>();
        static List<Orders> errorOrdersList = new List<Orders>();
        static Thread threadImport;

        public OrderImport()
        {
            InitializeComponent();
            openOrdersFile.Filter = "excel文件|*.xls";
            saveOrdersFile.Filter = "excel文件|*.xls";
        }


        private void btnBrowser_Click(object sender, EventArgs e)
        {
            DialogResult result = openOrdersFile.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK && openOrdersFile.CheckFileExists && openOrdersFile.CheckPathExists)
            {
                txtFilePath.Text = openOrdersFile.FileName;

                btnImport.Enabled = true;
            }
            else
            {
                MessageBox.Show("打开文件失败。");
                btnImport.Enabled = false;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            
            string fileName = string.Empty;

            fileName = txtFilePath.Text;

            importOrdersList = new List<Orders>();
            importOrdersList = GetOrdersFormExcel(fileName, ref message);

            if (!string.IsNullOrEmpty(message))
            {
                richtxtMessage.Text = message;
                return;
            }

            richtxtMessage.Text = string.Empty;
            btnImport.Enabled = false;
            btnBrowser.Enabled = false;
            btnExportErrorOrders.Visible = false;
            errorOrdersList = new List<Orders>();

            threadImport = new Thread(delegate()
            {
                int i = 1;                
                foreach (Orders temp in importOrdersList)
                {
                    StringBuilder sbMessage = new StringBuilder();
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            sbMessage.AppendLine("---------------------------");
                            sbMessage.AppendLine("正在处理第" + i + "条数据：");
                        }));
                    }
                    try
                    {
                        OrderServices.OrderServiceSoapClient client = new OrderServices.OrderServiceSoapClient();
                        message = client.ImportOrder(temp);
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                if (message == "0")
                                    message = "导入成功!";
                                else
                                {
                                    temp.Notes = message;
                                    errorOrdersList.Add(temp);
                                }
                                sbMessage.AppendLine("处理结果：" + message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }
                    catch (System.Exception ex)
                    {
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                temp.Notes = message;
                                errorOrdersList.Add(temp);
                                sbMessage.AppendLine("处理结果：" + ex.Message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }

                    i++;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        StringBuilder sbMessage = new StringBuilder();
                        sbMessage.AppendLine("---------------------------");
                        sbMessage.AppendLine(string.Format("全部处理完成，总共处理{0}条数据，{1}条数据导入成功，{2}条数据导入失败。", importOrdersList.Count, importOrdersList.Count - errorOrdersList.Count, errorOrdersList.Count));
                        richtxtMessage.AppendText(sbMessage.ToString());

                        btnBrowser.Enabled = true;
                        if (errorOrdersList.Count > 0)
                        {
                            btnExportErrorOrders.Visible = true;
                        }
                    }));
                }
            });

            threadImport.Start();
        }

        private static List<Orders> GetOrdersFormExcel(string fileName, ref string message)
        {
            List<Orders> ordersList = new List<Orders>();
            HSSFWorkbook workbook = null;
            StringBuilder sbMessage = new StringBuilder();

            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(fileStream);
                }
            }
            catch (Exception ex)
            {
                message = "文件读取发生问题：" + ex.ToString();
            }
            if (!string.IsNullOrEmpty(message))
            {
                return null;
            }

            HSSFSheet sheet = workbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            int rowNumber = -1;
            DateTime orderTime = DateTime.MinValue;
            string customerCode = string.Empty;

            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                if (rowNumber == -1)
                {
                    if (!DateTime.TryParse(row.GetCell(1).ToString(), out orderTime))
                    {
                        message = "订单时间格式错误：" + row.GetCell(1).ToString();
                        break;
                    }

                    customerCode = row.GetCell(3).StringCellValue;
                    rowNumber++;
                    continue;
                }
                if (rowNumber == 0)
                {
                    rowNumber++;
                    continue;
                }
                if (row.GetCell(0).CellType == HSSFCellType.BLANK)
                {
                    break;
                }

                Orders orders = new Orders();
                orders.OrderTime = orderTime;
                orders.CustomerCode = customerCode;
                orders.OrderNumberRef = row.GetCell(1).ToString();
                orders.OrderNumber = row.GetCell(2).ToString();
                orders.ChannelCode = row.GetCell(3).ToString();
                orders.CountryCN = row.GetCell(4).ToString();
                if (row.GetCell(5).ToString() == "DOC")
                    orders.ItemType = 0;
                else
                    orders.ItemType = 1;
                orders.Pieces = Convert.ToInt32(row.GetCell(6).ToString());
                orders.RealWeight = Convert.ToDouble(row.GetCell(7).ToString());
                orders.Status = 0;

                ordersList.Add(orders);
            }

            return ordersList;
        }

        private void btnExportErrorOrders_Click(object sender, EventArgs e)
        {
            DialogResult result = saveOrdersFile.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                ExportErrorOrders(saveOrdersFile.FileName);
            }
            else
            {
                MessageBox.Show("选择的保存文件失败。");
            }
            
        }

        private static void ExportErrorOrders(string fileName)
        {
            //创建xls文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet表单，默认名称为sheet1
            HSSFSheet sheet = workbook.CreateSheet("导入失败的订单数据");

            //创建行，设定第一行的表头
            HSSFRow rowFirst = sheet.CreateRow(0);
            //第1行 日期：2012年6月14日 21:53:24  客户代码：SZHK
            rowFirst.CreateCell(0, HSSFCellType.STRING).SetCellValue("日期：");
            rowFirst.CreateCell(1, HSSFCellType.STRING).SetCellValue(errorOrdersList.FirstOrDefault().OrderTime.ToString());
            rowFirst.CreateCell(2, HSSFCellType.STRING).SetCellValue("客户代码：");
            rowFirst.CreateCell(3, HSSFCellType.STRING).SetCellValue(errorOrdersList.FirstOrDefault().CustomerCode);

            //创建行，并设定第一行的表头
            HSSFRow rowTitle = sheet.CreateRow(1);
            
            rowTitle.CreateCell(0, HSSFCellType.STRING).SetCellValue("序号");
            rowTitle.CreateCell(1, HSSFCellType.STRING).SetCellValue("运单号");
            rowTitle.CreateCell(2, HSSFCellType.STRING).SetCellValue("转单号");
            rowTitle.CreateCell(3, HSSFCellType.STRING).SetCellValue("方式");
            rowTitle.CreateCell(4, HSSFCellType.STRING).SetCellValue("目的地");
            rowTitle.CreateCell(5, HSSFCellType.STRING).SetCellValue("品名");
            rowTitle.CreateCell(6, HSSFCellType.STRING).SetCellValue("件数");
            rowTitle.CreateCell(7, HSSFCellType.STRING).SetCellValue("实量");
            //rowTitle.CreateCell(8, HSSFCellType.STRING).SetCellValue("渠道");
            rowTitle.CreateCell(8, HSSFCellType.STRING).SetCellValue("失败原因");


            int rowNum = 1;
            foreach (Orders temp in errorOrdersList)
            {
                HSSFRow rowContent = sheet.CreateRow(rowNum + 1);//创建内容行

                //对第1行对应的单元格分别设定单元格内容属性和填充对应的值
                rowContent.CreateCell(0, HSSFCellType.STRING).SetCellValue(rowNum);
                rowContent.CreateCell(1, HSSFCellType.STRING).SetCellValue(temp.OrderNumberRef);
                rowContent.CreateCell(2, HSSFCellType.STRING).SetCellValue(temp.OrderNumber);
                rowContent.CreateCell(3, HSSFCellType.STRING).SetCellValue(temp.ChannelCode);
                rowContent.CreateCell(4, HSSFCellType.STRING).SetCellValue(temp.CountryCN);
                rowContent.CreateCell(5, HSSFCellType.STRING).SetCellValue(temp.ItemType.Value == 0 ? "DOC" : "其他");
                rowContent.CreateCell(6, HSSFCellType.STRING).SetCellValue(temp.Pieces.ToString());
                rowContent.CreateCell(7, HSSFCellType.STRING).SetCellValue(temp.RealWeight.ToString());
                rowContent.CreateCell(8, HSSFCellType.STRING).SetCellValue(temp.Notes);
                rowNum++;//动态增加行号
            }

            //写入excel文件
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);//把流写入文件
            }

            MessageBox.Show(rowNum - 1 + "条数据导出成功");//实际导出的数据比定义的行号少1            
        }
    }
}
